var express = require('express');
var morgan = require('morgan');
var socket = require('./SocketServer.js');
var myUtil = require("./util/myUtil.js");
var dataChecker = require("./util/dataChecker.js");

var app = express();
app.use(morgan('dev'));
socket.start();

// get: all online device
app.get('/devices/online', function(req, res) {
	var array = socket.clientItemMgr.getAllOnline();
	console.log("online size= " + array.length);
	res.send(JSON.stringify(array));
});

// send msg to one device
app.post('/device/sendmsg', function(req, res) {
	// TODO
	var body = '';
	req.on('data', function(chunk) {
		body += chunk;
	});

	req.on('end', function() {
		var json = parseInput(body);
		if (!json.data) {
			res.send(JSON.stringify(json));
			return;
		}

		var data = json.data;
		delete(json.data);
		res.send(JSON.stringify(json));

		socket.clientItemMgr.sendMsg(data.deviceUuid, data.msg);
	});
});

// error
app.use('/', function(req, res) {
	console.log('error: undefined path or method');
	res.end('error: undefined path or method');
})

var template = {
	"deviceUuid": ["xxx"],
	"msg": "xxx"
};

function parseInput(data) {
	var json = myUtil.str2Json(data);
	if (!json) {
		return myUtil.resJsonErr("canot parse to json");
	}

	var checkResult = dataChecker.check(template, json);
	if (checkResult.isOk === false) {
		return myUtil.resJsonErr(checkResult.msg);
	}

	return myUtil.resJsonOk(json);
}

app.listen(8081);
console.log('express start at 8081');